package com.james.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.james.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: JWTCheckFilter
 * @Author: JamesWang
 * @Date: 2021/4/21 20:56
 * @Description:
 * @Version:1.0
 */
@Configuration
public class JWTCheckFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * token的校验 因为每次请求都需要过网关 token 有 并且存在 redis 就放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.如果是登录 或者一些放行的接口 就不需要拦截
        // 2.拿到url地址
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        if (GatewayConstant.ALLOW_URL.contains(path)) {
            // 放行
            return chain.filter(exchange);
        }
        // 不是url 拿到token 放在header里面
        List<String> tokenHeaders = request.getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(tokenHeaders)) {
            String token = tokenHeaders.get(0);
            if (StringUtils.hasText(token)) {
                // 截取 bearer xxxx
                String jwt = token.replaceAll("bearer ", "");
                if (StringUtils.hasText(jwt) && redisTemplate.hasKey(GatewayConstant.TOKEN_JWT_PREFIX+jwt)) {
                    // jwt 不等空 redis也有 放行 把服务端变成有状态的 解决jwt登出问题
                    return chain.filter(exchange);
                }
            }
        }
        // 既不是放行的 也没有token 直接拦截 返回401 前台就会自动跳转到登录页面
        // 1.设置响应业务码
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type","application/json;charset=utf-8");
        // 2.设置业务响应码
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg","未授权");
        // 3.转换写出去
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 使用buffer工厂 将字节写出去
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
